package gui;

import classes.Ausencia;
import classes.AusenciaTipo;
import classes.Gozo;
import classes.Servidor;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.GeralException;
import fachada.Fachada;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author roberta.m.carvalho
 */
public class AusenciaCadastrar extends javax.swing.JFrame {

    ArrayList<Servidor> listaServ = new ArrayList<Servidor>();
    ArrayList<AusenciaTipo> listaAus = new ArrayList<AusenciaTipo>();

    public AusenciaCadastrar() {
        initComponents();
        this.setIconImage(Login.icone.getImage());
        carregarCombos();
        carregarLista();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoDias = new javax.swing.ButtonGroup();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        mesAquis1 = new com.toedter.calendar.JMonthChooser();
        anoAquis1 = new com.toedter.calendar.JYearChooser();
        jLabel2 = new javax.swing.JLabel();
        mesAquis2 = new com.toedter.calendar.JMonthChooser();
        anoAquis2 = new com.toedter.calendar.JYearChooser();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        mesGozo = new com.toedter.calendar.JMonthChooser();
        anoGozo = new com.toedter.calendar.JYearChooser();
        jLabel5 = new javax.swing.JLabel();
        textDias = new javax.swing.JTextField();
        cbServidor = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textObs = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        cbTipo = new javax.swing.JComboBox();
        btSalvar = new javax.swing.JButton();
        btCadastrarTipo = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tbAusencia = new javax.swing.JTable();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Férias / Afastamentos");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Período Aquisitivo:");

        anoAquis1.setDayChooser(null);
        anoAquis1.setMaximum(3000);
        anoAquis1.setStartYear(1990);

        jLabel2.setText("a");

        jLabel3.setText("Qtde dias:");

        jLabel4.setText("Previsão de Gozo:");

        jLabel5.setText("Servidor:");

        jLabel6.setText("Obs.:");

        textObs.setColumns(20);
        textObs.setLineWrap(true);
        textObs.setRows(5);
        jScrollPane1.setViewportView(textObs);

        jLabel7.setText("Tipo de Ausência:");

        cbTipo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cbTipoFocusGained(evt);
            }
        });

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        btCadastrarTipo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/adicionarP.png"))); // NOI18N
        btCadastrarTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCadastrarTipoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel7)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(mesGozo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(anoGozo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(textDias, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(mesAquis1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(anoAquis1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(mesAquis2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(anoAquis2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btCadastrarTipo)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                        .addComponent(btSalvar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btSalvar)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)
                            .addComponent(btCadastrarTipo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(mesAquis1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(anoAquis1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(mesAquis2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(anoAquis2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(mesGozo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(anoGozo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(cbServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbAusencia.setAutoCreateRowSorter(true);
        tbAusencia.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Cód.", "Tipo ", "Saldo", "Período Aquisitivo", "Servidor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbAusencia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbAusenciaMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tbAusencia);
        tbAusencia.getColumnModel().getColumn(0).setMinWidth(40);
        tbAusencia.getColumnModel().getColumn(0).setPreferredWidth(40);
        tbAusencia.getColumnModel().getColumn(0).setMaxWidth(50);
        tbAusencia.getColumnModel().getColumn(2).setMinWidth(55);
        tbAusencia.getColumnModel().getColumn(2).setPreferredWidth(55);
        tbAusencia.getColumnModel().getColumn(2).setMaxWidth(60);

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/excluir.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btExcluir)
                    .addComponent(btAlterar))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btExcluir)
                        .addGap(18, 18, 18)
                        .addComponent(btAlterar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        Ausencia a = new Ausencia();
        Fachada f = new Fachada();
        AusenciaTipo at = new AusenciaTipo();
        Servidor s = new Servidor();
        s = (Servidor) cbServidor.getSelectedItem();
        a.setServidor(s);
        at = (AusenciaTipo) cbTipo.getSelectedItem();
        a.setTipo(at);
        a.setSaldo(Integer.parseInt(textDias.getText()) - a.getSaldo());
        GregorianCalendar dataAquis1 = new GregorianCalendar(anoAquis1.getValue(), mesAquis1.getMonth(), 1);
        a.setAquisitivoInicial(dataAquis1);
        GregorianCalendar dataAquis2 = new GregorianCalendar(anoAquis2.getValue(), mesAquis2.getMonth(), 1);
        a.setAquisitivoFinal(dataAquis2);
        a.setObs(textObs.getText());
        GregorianCalendar dataGozo = new GregorianCalendar(anoGozo.getValue(), mesGozo.getMonth(), 1);
        a.setGozoI(dataGozo);
        dataGozo.add(Calendar.DAY_OF_MONTH, - 1);
        a.setGozoF(dataGozo);
        a.setTipoNome(at.getNome());
        a.setDias(Integer.parseInt(textDias.getText()));
        try {
            f.inserirAusencia(a);
            JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!");
            carregarLista();
            this.repaint();
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível cadastrar.\n" + ex);
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void tbAusenciaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbAusenciaMouseClicked
        if (evt.getClickCount() == 2 || evt.getButton() == MouseEvent.BUTTON1) {//se o clique for duplo
            DefaultTableModel modelo = (DefaultTableModel) tbAusencia.getModel();
            int r = tbAusencia.getSelectedRow();
            int atual = modelo.getValueAt(r, 0).hashCode();
            String nome = modelo.getValueAt(r, 4).toString();
            String tipo = modelo.getValueAt(r, 1).toString();
            Ausencia a = new Ausencia();
            a.setCod(atual);
            Fachada f = new Fachada();
            for (int s = 0; s < listaServ.size(); s++) {
                if (listaServ.get(s).getNomeExibicao().equals(nome)) {
                    cbServidor.setSelectedIndex(s);
                }
            }
            for (int t = 0; t < listaAus.size(); t++) {
                if (listaAus.get(t).getNome().equals(tipo)) {
                    cbTipo.setSelectedIndex(t);
                }
            }
            try {
                a = f.pesquisarAusencia(a);
                textDias.setText(String.valueOf(a.getSaldo()));
                mesAquis1.setMonth(a.getAquisitivoInicial().getMonth());
                anoAquis1.setValue(a.getAquisitivoInicial().getYear() + 1900);
                mesAquis2.setMonth(a.getAquisitivoFinal().getMonth());
                anoAquis2.setYear(a.getAquisitivoFinal().getYear() + 1900);
                mesGozo.setMonth(a.getGozoI().getMonth());
                anoGozo.setYear(a.getGozoI().getYear() + 1900);
                textObs.setText(a.getObs());

            } catch (ConexaoException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
            } catch (ConsultaException ex) {
                JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tela.\n" + ex);
            }
        }
    }//GEN-LAST:event_tbAusenciaMouseClicked

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        Ausencia a = new Ausencia();
        Fachada f = new Fachada();
        AusenciaTipo at = new AusenciaTipo();
        Servidor s = new Servidor();
        ArrayList<AusenciaTipo> listaAus = new ArrayList<AusenciaTipo>();
        ArrayList<Servidor> listaS = new ArrayList<Servidor>();
        try {
            listaAus = f.listarTipo();
            listaS = f.listarAtivos();
            int c = cbServidor.getSelectedIndex();
            int v = cbTipo.getSelectedIndex();
            int r = tbAusencia.getSelectedRow();
            int cod = tbAusencia.getValueAt(r, 0).hashCode();
            for (int b = 0; b < listaS.size(); b++) {
                if (c == b) {
                    s.setMatricula(listaS.get(b).getMatricula());
                    break;
                }
            }
            for (int g = 0; g < listaAus.size(); g++) {
                if (v == g) {
                    at.setCodTipo(listaAus.get(g).getCodTipo());
                    at.setNome(listaAus.get(g).getNome());
                    break;
                }
            }
            a.setCod(cod);
            a.setServidor(s);
            a.setTipo(at);
            a.setSaldo(Integer.parseInt(textDias.getText()) - a.getSaldo());
            GregorianCalendar dataAquis1 = new GregorianCalendar(anoAquis1.getValue(), mesAquis1.getMonth(), 1);
            a.setAquisitivoInicial(dataAquis1);
            GregorianCalendar dataAquis2 = new GregorianCalendar(anoAquis2.getValue(), mesAquis2.getMonth(), 1);
            a.setAquisitivoFinal(dataAquis2);
            a.setObs(textObs.getText());
            GregorianCalendar dataGozo = new GregorianCalendar(anoGozo.getValue(), mesGozo.getMonth(), 1);
            a.setGozoI(dataGozo);
            dataGozo.add(Calendar.DAY_OF_MONTH, - 1);
            a.setGozoF(dataGozo);
            a.setTipoNome(at.getNome());
            f.alterarAusencia(a);
            carregarLista();
            JOptionPane.showMessageDialog(null, "Alterado com sucesso!");
            this.repaint();
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível alterar.\n" + ex);
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir?", "Alerta!", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            int size = tbAusencia.getSelectedRowCount();
            if (size > 1) {
                JOptionPane.showMessageDialog(null, "Selecione apenas um tipo por vez!");
                tbAusencia.setSelectionMode(1);
            } else {
                Ausencia at = new Ausencia();
                Gozo gozo = new Gozo();
                Fachada f = new Fachada();
                ArrayList<Ausencia> lista;
                try {
                    lista = f.listarAusencia();
                    int r = tbAusencia.getSelectedRow();
                    for (int i = 0; i < lista.size(); i++) {
                        if (i == r) {
                            at.setCod(lista.get(i).getCod());
                            f.deletarAusencia(at, gozo);
                            carregarLista();
                        }
                    }
                } catch (ConexaoException ex) {
                    JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
                } catch (ConsultaException ex) {
                    JOptionPane.showMessageDialog(null, "Ausencia em uso!");
                }
            }
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void btCadastrarTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCadastrarTipoActionPerformed
        // TODO add your handling code here:
        AusenciaTipoCadastrar tac = new AusenciaTipoCadastrar();
        tac.setVisible(true);
        tac.setLocationRelativeTo(null);
    }//GEN-LAST:event_btCadastrarTipoActionPerformed

    private void cbTipoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbTipoFocusGained
        // TODO add your handling code here:
        carregarCombos();
    }//GEN-LAST:event_cbTipoFocusGained
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AusenciaCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AusenciaCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AusenciaCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AusenciaCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new AusenciaCadastrar().setVisible(true);
            }
        });
    }

    public final void carregarCombos() {
        Fachada fachada = new Fachada();
        try {
            listaAus = fachada.listarTipo();
            listaServ = fachada.listarAtivos();
            cbTipo.removeAllItems();
            cbServidor.removeAllItems();
            for (int i = 0; i < listaAus.size(); i++) {
                AusenciaTipo at = new AusenciaTipo();
                at = listaAus.get(i);
                cbTipo.addItem(at);
            }
            for (int cE = 0; cE < listaServ.size(); cE++) {
                Servidor serv = new Servidor();
                serv = listaServ.get(cE);
                cbServidor.addItem(serv);
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tela.\n" + ex);
        }
    }

    public void carregarLista() {
        try {
            Fachada f = new Fachada();
            DefaultTableModel modeloAus = (DefaultTableModel) tbAusencia.getModel();
            modeloAus.setNumRows(0);
            ArrayList<Ausencia> lista = new ArrayList<Ausencia>();
            lista = f.listarAusencia();
            for (int i = 0; i < lista.size(); i++) {
                Ausencia.id = lista.get(i).getCod();
                String nome = "", tipo = "";
                ArrayList<Servidor> listaP = (ArrayList<Servidor>) f.listarAtivos();
                ArrayList<AusenciaTipo> listaT = (ArrayList<AusenciaTipo>) f.listarTipo();
                DateFormat formatdata = new SimpleDateFormat("MM-yyyy");
                Date dataIni = lista.get(i).getAquisitivoInicial();
                String dataI = (formatdata.format(dataIni));
                Date dataFim = lista.get(i).getAquisitivoFinal();
                String dataF = (formatdata.format(dataFim));

                for (Servidor serv : listaP) {
                    if (serv.getMatricula() == lista.get(i).getServidor().getMatricula()) {
                        nome = serv.getNomeExibicao();
                    }
                }
                for (AusenciaTipo t : listaT) {
                    if (t.getCodTipo() == lista.get(i).getTipo().getCodTipo()) {
                        tipo = t.getNome();
                    }
                }

                modeloAus.addRow(new Object[]{lista.get(i).getCod(), tipo, lista.get(i).getSaldo(), dataI + " a " + dataF, nome});
            }
            tbAusencia.setModel(modeloAus);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tabela de Férias!\n" + ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JYearChooser anoAquis1;
    private com.toedter.calendar.JYearChooser anoAquis2;
    private com.toedter.calendar.JYearChooser anoGozo;
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btCadastrarTipo;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btSalvar;
    private javax.swing.JComboBox cbServidor;
    private javax.swing.JComboBox cbTipo;
    private javax.swing.ButtonGroup grupoDias;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private com.toedter.calendar.JMonthChooser mesAquis1;
    private com.toedter.calendar.JMonthChooser mesAquis2;
    private com.toedter.calendar.JMonthChooser mesGozo;
    private javax.swing.JTable tbAusencia;
    private javax.swing.JTextField textDias;
    private javax.swing.JTextArea textObs;
    // End of variables declaration//GEN-END:variables
}
